package com.newly.common.core.auth;

import com.newly.common.base.entity.sys.menu.po.MenuPo;
import com.newly.common.mapper.sys.MenuMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * oauth2资源服务器
 *
 * @author: guan
 * @date: 2021/06/20/2:15
 */
@Slf4j
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class ResourcesServerConfig extends ResourceServerConfigurerAdapter {


    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 让资源服务器从tokenStore中拿到token
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 获取所有菜单
        List<MenuPo> menuPos = menuMapper.selectList(null);

        // 封装需要放行的路劲,比如网关需要
        Set<String> accessOpens = new HashSet<>(32);

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry =
                http.csrf().disable().authorizeRequests();

        /*for (MenuPo menuPo : menuPos) {
            String serverUri = menuPo.getServerUri();
            String auth = menuPo.getAuth();
            if (StrUtil.isBlank(serverUri)) {
                log.error("The menu has no serverUri property, Skipped. menuPo = {}", menuPo);
                continue;
            }
            if (StrUtil.isBlank(auth)) {
                log.error("The menu has no auth property, Skipped. menuPo = {}", menuPo);
                continue;
            }

            if (menuPo.getAccess().equals(MenuConstant.Access.OPEN.getCode())) {
                // 放行权限
                accessOpens.add(serverUri);
                registry.antMatchers(serverUri).permitAll();
            } else {
                // 鉴权
                registry.antMatchers(serverUri).hasAnyAuthority(menuPo.getAuth());
            }
        }*/
        registry.antMatchers("/**").permitAll();

        registry.anyRequest().authenticated()
                .and()
                .formLogin().permitAll();

    }




    /*@Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        // 对称解密
        // jwtAccessTokenConverter.setSigningKey(CommonConstant.JWT_SIGNING_KEY);

        // 非对称解密
        ClassPathResource resource = new ClassPathResource(AuthConstant.JWT_SIGNING_SLL_PUBLIC_FILE_NAME);
        String publicKey = null;
        try {
            publicKey = FileUtil.readString(resource.getFile(), Charset.defaultCharset());
        } catch (IOException e) {
            e.printStackTrace();
        }
        jwtAccessTokenConverter.setVerifierKey(publicKey);
        return jwtAccessTokenConverter;
    }*/

    /* @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        // 对称加密
        //jwtAccessTokenConverter.setSigningKey(CommonConstant.JWT_SIGNING_KEY);

        // 非对称加密
        ClassPathResource resource = new ClassPathResource(AuthConstant.JWT_SIGNING_SLL_PRIVATE_FILE_NAME);
        // 私钥和私钥密码得到私钥工厂
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource, AuthConstant.JWT_SIGNING_SLL_PASS.toCharArray());
        // 别名拿到私钥
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair(AuthConstant.JWT_SIGNING_SLL_ALIAS);
        jwtAccessTokenConverter.setKeyPair(keyPair);
        return jwtAccessTokenConverter;
    }*/
}
